package cn.sdormitory.smartdor.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import cn.sdormitory.basedata.dao.BStudentDao;
import cn.sdormitory.smartdor.dao.StudentTrajectoryDao;
import cn.sdormitory.basedata.entity.BStudent;
import cn.sdormitory.smartdor.entity.StudentTrajectory;
import cn.sdormitory.smartdor.service.ExternalInterfaceService;
import cn.sdormitory.wx.entity.WechatPushMessage;
import cn.sdormitory.wx.mapper.WechatPushMessageMapper;
import cn.sdormitory.wx.service.WxPushInfoService;
import cn.sdormitory.wx.utils.WXUtil;
import cn.sdormitory.wx.utils.WeatherDataCreator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @className: ExternalInterfaceServiceImpl
 * @author: Alex
 * @date: 2024/9/25
 **/
@Slf4j
@Service
public class ExternalInterfaceServiceImpl implements ExternalInterfaceService {

	private String student_leave_template_id = "WpIEFabKtOPhq1vXuEWpx7X8LMNIv9upkMMwih-WpwI";

	@Resource
	private BStudentDao bStudentDao;

	@Resource
	private StudentTrajectoryDao studentTrajectoryDao;

	@Autowired
	WeatherDataCreator weatherDataCreator;

	@Autowired
	WxPushInfoService wxPushInfoService;

	@Autowired
	StringRedisTemplate redisTemplate;
	
	@Resource
	private WechatPushMessageMapper wechatPushMessageMapper;

	@Autowired
	WXUtil wxUtil;

	@Override
	public Boolean receiveSchoolGateEntryAndExitInfo(List<Map<String, String>> records) {
		//1.根据userId即学生id进行分组
		Map<String, List<Map<String, String>>> groupByUserId = records.stream()
				.collect(Collectors.groupingBy(item -> item.get("userId")));

		// 门口门禁的刷脸数据入库
		Set<String> keySet = groupByUserId.keySet();
		List<String> stuIdList = new ArrayList<>(keySet);
		List<String> newStuIdList = new ArrayList<>();
		for (String studentId : stuIdList) {
			if (studentId.endsWith("A")) {
				String replace = studentId.substring(0, studentId.length() - 1);
				newStuIdList.add(replace);
				continue;
			}
			newStuIdList.add(studentId);
		}

		List<BStudent> bStudents = bStudentDao.selectBatchIds(newStuIdList);

		Map<Long, List<BStudent>> students = bStudents.stream().collect(Collectors.groupingBy(BStudent::getId));

		List<StudentTrajectory> trajectoryList = new ArrayList<>();

		for (Map<String, String> map : records) {
			String studentId = map.get("userId");
			String date = map.get("stuTime");
			String deviceName = map.get("deviceName");
			String snapFtpUrl = map.get("snapFtpUrl");
			String direction = map.get("direction");
			String cardName = map.get("cardName");
			if (studentId.endsWith("A")) {
				studentId = studentId.substring(0, studentId.length() - 1);
			}

			List<BStudent> bStudents1 = students.get(Long.valueOf(studentId));

			StudentTrajectory studentTrajectory = new StudentTrajectory();
			studentTrajectory.setStudentType("教职工");
			// 匹配到对应的学生信息
			if (CollectionUtil.isNotEmpty(bStudents1)) {
				// 则需要发送微信推送
				// 用来获取微信用户openId
//			    BStudent bStudent = new BStudent();
//				bStudent.setStudentName("test");
				BStudent bStudent = bStudents1.get(0);
				studentTrajectory.setStudentType("住宿生");
				if (StringUtils.equals(bStudent.getStatus(), "0")) {
					studentTrajectory.setStudentType("走读生");
				}
				studentTrajectory.setClassName(bStudent.getClassName());
				studentTrajectory.setDormitoryInfo(bStudent.getDormitoryName());
//				bStudent.setParentWxOpenId("o2Qfr6MkuT-QbNUvlgTs64EpZqrA");
				// 如果有记录父母的wxopenid, 则发送订阅信息
				if (StringUtils.isNotBlank(bStudent.getParentWxOpenId())) {
					String studentStatus = "到校";
					if (direction.equals("2")) {
						studentStatus = "离校";
					}
					try {
						String url = "pages_duty/parent/goOutDetail?studentId="+bStudent.getId()+
								"&faceTime="+date+"&type=trajectory";
						// 发送模板消息
						Map<String, Object> weatherDataMap = weatherDataCreator.createStudentLeaveDataMap(bStudent.getStudentName(),
								studentStatus, date);
						JSONObject jsonObject = wxUtil.sendInfo(bStudent.getParentWxOpenId(), student_leave_template_id
								, weatherDataMap, url);
						
						WechatPushMessage wechatPushMessage = new WechatPushMessage();
						wechatPushMessage.setTemplateId(student_leave_template_id);
						wechatPushMessage.setContent(weatherDataMap.toString());
						wechatPushMessage.setReceiverOpenId(bStudent.getParentWxOpenId());
						
						if (jsonObject != null && "0".equals(jsonObject.get("errcode").toString())) {
							// 发送成功
							wechatPushMessage.setStatus(true);
						} else {
							wechatPushMessage.setStatus(false);
						}
						wechatPushMessage.setBackInfo(jsonObject.get("errmsg").toString());
						wechatPushMessageMapper.insert(wechatPushMessage);
					} catch (Exception e) {
						log.error("{} 进出校门,发送微信推送失败!", bStudent.getStudentName());
					}
					
				} else {
					log.info("{} 父母没有绑定服务号，没有微信openid！", bStudent.getStudentName());
				}
			}

			studentTrajectory.setCardName(cardName);
			studentTrajectory.setStudentId(Long.parseLong(studentId));
			studentTrajectory.setDeviceAddr(deviceName);
			studentTrajectory.setFaceTime(date);
			studentTrajectory.setSnapFtpUrl(snapFtpUrl);
			studentTrajectory.setType(direction);
			studentTrajectory.setCreateTime(new Date());
			trajectoryList.add(studentTrajectory);
			log.info("========>  ReceiveSchoolGateEntryAndExitInfoEnd");

		}

		// 获取数据了，先入库
		if (CollectionUtil.isNotEmpty(trajectoryList)) {
			studentTrajectoryDao.insertBatch(trajectoryList);
		}
		return true;
	}
}
